<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;    //引用http请求类
use App\Exceptions\BasicException;  //引入框架异常处理类
use Illuminate\Support\Facades\Hash;    //引入hash
use App\Services\Cache\AdminCacheService;   //admin缓存
use App\Services\Tools\JwtService;    //引入JWT服务
use App\Services\Tools\FileService;   //引入文件处理类
use Illuminate\Support\Facades\DB;
use App\Response\Response;

class SuperAdminController extends BaseController
{


    /**
     * 修复单厅数据
     * @param Request $request
     * @return string
     */
    public function synchro_data(Request $request)
    {

        $room_id = $request->input('room_id',0);

        $start_at = $request->input('start_at',0);

        $end_at = $request->input('end_at',0);

        $hall_id = $request->input('hall_id',0);

        $give_id_array = app('model_sc_income')->whereBetween('add_time',[$start_at,$end_at])->where('room_id',$room_id)->pluck('give_id')->toArray();

        $list = app('model_give_gift')->whereBetween('add_time',[$start_at,$end_at])->where('room_id',$room_id)->whereNotIn('id',$give_id_array)->get();

        $sociatys = app('model_sc_sociaty')->where('sociaty_id',$hall_id)->where('type',2)->first();

        foreach ($list as &$val) {

            //赠送时间要大于开厅时间
            if($val->add_time > $sociatys->add_time) {

                $type = 2;//流水类别1主播产生的流水(成员流水)2单纯房间产生的流水(房间流水)
                $sociaty_id = 0;    //记录当时公会的ID
                $relations = 0; //0无1直属2挂靠
                //查看发生交易时,主播和厅的关系--查询在收支记录之前的最新一次的加入厅的记录 todo:重构此处的逻辑,改为deamon的形式
                $user_record = app('model_sc_user_history')->where(['user_id'=>$val->gift_user,'sociaty_id'=>$sociatys->sociaty_id])
                    ->where('add_time','<',$val->add_time)->orderBy('add_time','desc')->first();
                if(!empty($user_record) && $user_record->type == 1) {
                    $type = 1;
                }

                //查看最近的一次厅挂靠记录
                $sociaty_record = app('model_sc_sociaty_history')->where('hall_id',$sociatys->sociaty_id)
                    ->where('add_time','<',$val->add_time)->whereIn('type',[1,2])
                    ->orderBy('add_time','desc')->first();

                if(!empty($sociaty_record) && $sociaty_record->type == 1) {
                    $sociaty_id = $sociaty_record->sociaty_id;
                    $relations = $sociaty_record->relations;
                }

                $is_record = true;
                if($is_record) {
                    //只记录一次
                    $data = [
                        'user_id' => $val->gift_user,
                        'uid' => $val->user_id,
                        'sc_id' => $sociaty_id,
                        'hall_id' => $sociatys->sociaty_id,
                        'amount' => intval($val->total_price),
                        'add_time' => $val->add_time,
                        'ctime' => time(),
                        'room_id' => $val->room_id,
                        'give_id' => $val->id,
                        'type' => $type,
                        'relations' => $relations

                    ];

                    //备份记录
                    app('model_sc_income')->create($data);

                }
            }
        }

        return Response::sendData('同步成功');

    }


    /**
     * 删除时间段内的重复流水数据--周日前使用
     * @param Request $request
     * @return string
     */
    public function delete_repeat_data(Request $request)
    {
        
        $start_at = $request->input('start_at',0);

        $end_at = $request->input('end_at',0);

        $give_ids = app('model_sc_income')->whereBetween('add_time',[$start_at,$end_at])
            ->groupBy('give_id')->having(DB::raw('count(give_id)'), '>', 1)->pluck('give_id')->toArray();

        $income_ids = app('model_sc_income')->whereIn('give_id',$give_ids)->get()->groupBy('give_id')->map(function ($group) {
            $sorted = $group->sortBy('income_id');
            return $sorted->first();
        })->pluck('income_id')->toArray();

        $res = app('model_sc_income')->whereIn('income_id',$income_ids)->delete();

        if($res) return Response::sendData('删除成功,共删除了'.count($give_ids).'条重复数据');

        return Response::sendData('删除失败');

    }


    /**
     * 修复春节活动榜单数据
     * @param Request $request
     * @return string
     */
    public function repair_spring_data(Request $request)
    {
        $start_at = $request->input('start_at',0);

        $end_at = $request->input('end_at',0);

        //查出所有个人房房主ID
        $user_ids = app('model_user_room')->where('sys_type_id',38)->pluck('user_id')->toArray();

        //查询所有个人房房主的财富值(送礼物)
        $rich_list = app('model_give_gift')->whereBetween('add_time',[$start_at,$end_at])->whereIn('user_id',$user_ids)->whereIn('gift_id',[472,473,474])
            ->select('user_id',DB::raw('sum(total_price) as total'))->groupBy('user_id')->get()->toArray();

        //查询所有个人房房主的魅力值(收礼物)
        $charm_list = app('model_give_gift')->whereBetween('add_time',[$start_at,$end_at])->whereIn('gift_user',$user_ids)->whereIn('gift_id',[472,473,474])
            ->select('gift_user',DB::raw('sum(total_price) as total'))->groupBy('gift_user')->get()->toArray();

        //插入redis排行榜中---财富榜
        foreach($rich_list as $val)
        {
            app('redis')->zincrby('ACTIVITY:sf_rank:rich_rank',$val['total'],$val['user_id']);
        }

        //魅力榜
        foreach($charm_list as $val)
        {
            app('redis')->zincrby('ACTIVITY:sf_rank:charm_rank',$val['total'],$val['gift_user']);
        }

        return Response::sendData('修复成功');

    }


    /**
     * 退出公会
     * @param Request $request
     * @return string
     * @throws BasicException
     */
    public function quit_sociaty_member(Request $request)
    {
        $user_code = $request->input('user_code',0);

        $user = app('model_user_data')->where('user_code',$user_code)->first();

        if(empty($user)) throw new BasicException(93046);

        $user_id = $user->user_id;

        $sociaty_user = app('model_sc_sociaty_user')->where('user_id',$user_id)->first();

        if(empty($sociaty_user)) throw new BasicException(20007);


        //开启事务执行审核操作
        DB::beginTransaction();
        try{

            //判断是否有申请退出记录
            $apply = app('model_sc_user_apply')->where(['user_id'=>$user_id,'type'=>2,'status'=>1])->first();

            if(!empty($apply)) {

                //有申请退出记录,则处理退出记录
                $res = app('model_sc_user_apply')->where(['user_id'=>$user_id,'type'=>2,'status'=>1])->update(['status'=>2,'update_time'=>time()]);
                if(!$res) throw new BasicException(20007);
            }

            //执行退出删除操作
            $rn = app('model_sc_sociaty_user')->where(['user_id'=>$user_id])->delete();
            if(!$rn) throw new BasicException(20007);

            $log_data = [
                'user_id' => $user_id,
                'sociaty_id' => $sociaty_user->sociaty_id,
                'add_time' => time(),
                'type' => 2
            ];

            $ra = app('model_sc_user_history')->create($log_data);
            if(!$ra) throw new BasicException(20007);

            DB::commit();

        }catch (\Exception $e) {

            DB::rollBack();
            throw new BasicException(20007);
        }

        return Response::sendData('用户' . $user_code . '退出公会成功');
    }


    /**
     * 同步所有厅数据
     * @param Request $request
     * @return string
     */
    public function synchro_all_data(Request $request)
    {
        set_time_limit(0);

        $start_at = $request->input('start_at',0);

        $end_at = $request->input('end_at',0);

        $list = app('model_sc_sociaty')->where('type',2)->where('parent_id','>',0)->select('room_id','sociaty_id')->get()->toArray();

        foreach($list as $val)
        {
            $this->update_single_sociaty_data($val['room_id'],$val['sociaty_id'],$start_at,$end_at);
        }

        return Response::sendData('所有厅数据全部同步完成');
    }


    /**
     * 同步单厅数据
     * @param $room_id
     * @param $hall_id
     * @param $start_at
     * @param $end_at
     * @return string
     */
    public function update_single_sociaty_data($room_id,$hall_id,$start_at,$end_at)
    {

        $give_id_array = app('model_sc_income')->whereBetween('add_time',[$start_at,$end_at])->where('room_id',$room_id)->pluck('give_id')->toArray();

        $list = app('model_give_gift')->whereBetween('add_time',[$start_at,$end_at])->where('room_id',$room_id)->whereNotIn('id',$give_id_array)->get();

        $sociatys = app('model_sc_sociaty')->where('sociaty_id',$hall_id)->where('type',2)->first();

        foreach ($list as &$val) {

            //赠送时间要大于开厅时间
            if($val->add_time > $sociatys->add_time) {

                $type = 2;//流水类别1主播产生的流水(成员流水)2单纯房间产生的流水(房间流水)
                $sociaty_id = 0;    //记录当时公会的ID
                $relations = 0; //0无1直属2挂靠
                //查看发生交易时,主播和厅的关系--查询在收支记录之前的最新一次的加入厅的记录 todo:重构此处的逻辑,改为deamon的形式
                $user_record = app('model_sc_user_history')->where(['user_id'=>$val->gift_user,'sociaty_id'=>$sociatys->sociaty_id])
                    ->where('add_time','<',$val->add_time)->orderBy('add_time','desc')->first();
                if(!empty($user_record) && $user_record->type == 1) {
                    $type = 1;
                }

                //查看最近的一次厅挂靠记录
                $sociaty_record = app('model_sc_sociaty_history')->where('hall_id',$sociatys->sociaty_id)
                    ->where('add_time','<',$val->add_time)->whereIn('type',[1,2])
                    ->orderBy('add_time','desc')->first();

                if(!empty($sociaty_record) && $sociaty_record->type == 1) {
                    $sociaty_id = $sociaty_record->sociaty_id;
                    $relations = $sociaty_record->relations;
                    //重复判断是否是成员流水
                    if($type == 2) {

                        $hall_array = app('model_sc_sociaty')->where('parent_id',$sociaty_record->sociaty_id)->pluck('sociaty_id')->toArray();

                        if(!empty($hall_array)) {
                            $user_array = app('model_sc_sociaty_user')->whereIn('sociaty_id',$hall_array)->pluck('user_id')->toArray();
                            if(in_array($val->gift_user,$user_array))
                            {
                                $type = 1;
                            }
                        }
                    }



                }

                $is_record = true;
                if($is_record) {
                    //只记录一次
                    $data = [
                        'user_id' => $val->gift_user,
                        'uid' => $val->user_id,
                        'sc_id' => $sociaty_id,
                        'hall_id' => $sociatys->sociaty_id,
                        'amount' => intval($val->total_price),
                        'add_time' => $val->add_time,
                        'ctime' => time(),
                        'room_id' => $val->room_id,
                        'give_id' => $val->id,
                        'type' => $type,
                        'relations' => $relations

                    ];

                    //备份记录
                    app('model_sc_income')->create($data);

                }
            }
        }

        return true;
    }





}